package net.hnedu.search.resource;

import java.util.TimerTask;
import java.util.Collection;
import java.util.Iterator;
import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.lucene.index.IndexWriter;
import net.hnedu.factory.ResResourceFactory;
import net.hnedu.map.ResResource;

public class RebuildResourceIndex
    extends TimerTask {
  private static Log log = LogFactory.getLog(RebuildResourceIndex.class);

  public static final int MERGE_FACTOR = 20;
  private int maxMemberID = 0;

  RebuildResourceIndex(int maxMemberID) {
    this.maxMemberID = maxMemberID;
  }

  public void run() {
    long start = System.currentTimeMillis();
    Collection companies = null;
    companies = ResResourceFactory.getInstance().getResResources();
    if (companies == null) return;
    IndexWriter writer = null;
    try {
      writer = ResourceIndex.getIndexWriter(true);
      writer.mergeFactor = MERGE_FACTOR;

      int i = 0;
      for (Iterator iter = companies.iterator(); iter.hasNext(); ) {
        ResResource res = (ResResource)iter.next();
        ResourceIndex.doIndexRes(res,writer);
        i++;
      }
      writer.optimize();
      log.info("Rebuilding index finished successfully! " + i + " res(s) indexed");
    } catch(Exception e) {
      log.error(e);
    } finally {
      try {
        if (writer != null) {
          writer.close();
        }
      }
      catch (IOException ignore) {
      }
    }
    log.info("RebuildResource took " + (System.currentTimeMillis() - start) + " ms");
  }
}
